<?php
/**
 * 微信操作
 * @author zlj <389843954@qq.com>
 */
namespace app\common\model;
use app\common\model\User;
use app\common\model\Dev_info;
use app\common\model\Company_dev;
use app\common\model\Alarm_info;
use app\common\model\Qrcode;
Vendor('Wechat.Wechat');
class Wechat
{
	/**
     * 查出用户相关信息
     * @param [string] $openid [微信openid]
     */
    public function follows($openid){
         $userModel = new User();
         $field = 'id,name,type,openid,ms,valid';
         $where = ['openid'=>$openid];
         $res = $userModel->getOne($field,$where);
         if(!$res){
   		    //获取用户唯一标识 unionid
            $options["appid"] = config("WECHAT_APPID");
            $options["appsecret"] = config("WECHAT_APPSERVER");
            $weObj = new \Wechat($options);
            $info = $weObj->getUserInfo($openid);

            if($info["openid"]){
                //如果不存在,则添加一条此openid的信息
                $add["openid"] = $openid;
                $add["t1"] = time();
                $add["ms"] = isset($info["unionid"])?$info["unionid"]:'';
                $userModel->save($add);
            }
         }
         return true;
    }

    /**
     * 发送微信警报
     * @param  [string] $dev_id [设备guid1]
     * @param  [string] $type [1:报警  2：警报解除  3:掉线]
     * @param  [string] $reason [警报内容]
     * @return [type]         [description]
     */
    public function wechat_send($dev_id,$type,$reason=""){

        $devinfoModel = new Dev_info();
        $info = $devinfoModel->getOne(["guid1"=>$dev_id],'owner,name');
        if(0>=$info["owner"]){
            //此设备未绑定用户
            return false;
        }

        $alarmModel = new Alarm_info();
        $res = $alarmModel->getRedisAddr($dev_id);
        if($res){
            foreach ($res as $k=>$value) {
                if(!empty($value["weixin"])){
                    
                    $return = $this->sends($value["weixin"],$dev_id,$info["name"],$type,$reason);

                    //写日志
                    if($type!=2){
                        if($return){
                            \Think\Log::write('微信_警报上传_发送成功',$dev_id."_".$k);
                        }else{
                            \Think\Log::write('微信_警报上传_发送失败',$dev_id."_".$k);
                        }
                    }else{
                        if($return){
                            \Think\Log::write('警报_警报撤销_发送成功',$dev_id."_".$k);
                        }else{
                            \Think\Log::write('微信_警报撤销_发送失败',$dev_id."_".$k);
                        }
                    }
                }
            }
        }
    }

    /**
     * 微信发送信息
     * @param  [string] $openid   [用户openid]
     * @param  [string] $dev_id   [设备id]
     * @param  [string] $dev_name [设备名]
     * @param  [string] $reason   [警报标题]
     * @return [bool]           [true:成功 false:失败]
     */
    public function sends($openid,$dev_id,$dev_name,$type,$reason=""){
        $this->follows($openid);

        $options["appid"] = config("WECHAT_APPID");
        $options["appsecret"] = config("WECHAT_APPSERVER");

        $weObj = new Wechat($options);
       
        // $user["third_id"] = "ojM70wGg15zCctbLDQIJku3uwKes";
        //THZWrb81ML4EAEtovpOxYGEUqtTTHrH0s-HDqd80w-g
        //s   ojM70wNZid_7vLP08offlqMZ0P2U
        //z   ojM70wGg15zCctbLDQIJku3uwKes
        
        // $user["third_id"] = "ojM70wE2EK4zlZB-pywg8rJO1-pQ";
        date_default_timezone_set('PRC');
        $time = date("Y-m-d H:i:s",time());
        if($type==3){
            $remark = "请注意：此设备已掉线!";
            $val = "掉线报警";
        }elseif($type==2){
            $remark = "请注意：此设备已解除警报";
            $val = "报警解除";
        }else{
            if($reason){
                $val = $reason;
            }else{
                $val = "出现异常";
            }
            
            $remark = "请注意：以免给你带来损失!";
        }

        $data = array(
            "touser"=>$openid,
            "template_id"=>"UEki7S7XI9-uOoDwz8PBiBY7BijUGcZTt71h7H0XXxw",
            "url"=>"",
            "topcolor"=>"#FF0000",
            "data"=>array(
                 "first"=>array(
                     "value"=>"您好,智能设备报告警报信息",
                     "color"=>"#173177"
                 ),
                 "keyword1"=>array(
                     "value"=>$dev_id,
                     "color"=>"#173177"
                 ),
                 "keyword2"=>array(
                     "value"=>$dev_name,
                     "color"=>"#173177"
                 ),
                 "keyword3"=>array(
                     "value"=>$val,
                     "color"=>"#173177"
                 ),
                 "keyword4"=>array(
                     "value"=>$time,
                     "color"=>"#173177"
                 ),
                 "remark"=>array(
                     "value"=>$remark,
                     "color"=>"#173177"
                 ),
            )
        );
        $res = $weObj->sendTemplateMessage($data);
     
        if($res){
           return true;
        }else{
           return false;
        }
    }

    /**
     * 生成二维码并保存记录
     * @param  [string] $dev_id [设备号]
     * @return [array]   [true:成功 fasle:失败]
     */
    public function createCode($dev_id){

        $companyModel = new Company_dev();
        $guid2 = $companyModel->getOne(["guid1"=>$dev_id],'guid2');
        if(!$guid2){
            return array("code"=>false,"msg"=>"错误操作");
        }

        //存在直接返回
        $path = config("WETCHAT_CODE");
        $filename = $path.$dev_id.".jpg";
        //如果存在则不进行拉去了
        if(file_exists($filename)){
            return array("code"=>true,"msg"=>$filename);
        }
        if($guid2){

             //通过微信生成二维码
             $options["appid"] = config("WECHAT_APPID");
             $options["appsecret"] = config("WECHAT_APPSERVER");
             $weObj = new \Wechat($options);

             $code = "qrscene_".$dev_id."_".$guid2["guid2"];
             $return = $weObj->getQRCode($code,2);
             if(!is_bool($return)){
                $codeModel = new Qrcode();

                $codeModel->del(array("guid1"=>$dev_id));

                $add["guid1"] = $dev_id;
                $add["ticket"] = $return["ticket"];
                $add["qurl"] = $return["url"];
                $res = $codeModel->save($add);
                if($res){
                    $this->downFromWeiXin($dev_id,$return["ticket"]);

                    return array("code"=>true,"msg"=>$filename);
                }else{
                    return array("code"=>false,"msg"=>"生成失败");
                }
             }else{
                return array("code"=>false,"msg"=>"生成失败");
             }

        }else{
            return array("code"=>false,"msg"=>"生成失败");
        }
    }

    /**
     * 下载设备二维码到服务器
     * @param  [string] $dev_id [设备guid1(用于生产图片名)]
     * @param [string] $ticket [二维码ticket, 默认为 false]
     * @return [string]         [图片地址]
     */
    public function downFromWeiXin($dev_id,$ticket=false){

        $path = config("WETCHAT_CODE");
        $filename = $path.$dev_id.".jpg";
        //如果存在则不进行拉去了
        if(file_exists($filename)){
            return $filename;
        }
        if(!$ticket){
            $codeModel = new Qrcode();
            $tic = $codeModel->getOne(["guid1"=>$dev_id],'ticket');
            if($tic){
                 $ticket = $tic["ticket"];
            }else{
                return false;
            }
        }

        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);

        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file,$package)) {
                fclose($local_file);
                return $filename;
            }
        }
    }
}